package com.example.shuiyin.controller;

import com.example.shuiyin.dto.ApiResponse;
import com.example.shuiyin.dto.BatchProcessRequest;
import com.example.shuiyin.dto.ProcessResultDto;
import com.example.shuiyin.dto.TaskStatusDto;
import com.example.shuiyin.dto.UploadResultDto;
import com.example.shuiyin.dto.WatermarkAddRequest;
import com.example.shuiyin.dto.WatermarkRemoveRequest;
import com.example.shuiyin.dto.watermark.WatermarkHistoryResponse;
import com.example.shuiyin.entity.WatermarkRecord;
import com.example.shuiyin.service.WatermarkService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/watermark")
@RequiredArgsConstructor
@Slf4j
public class WatermarkController {

    private final WatermarkService watermarkService;

    /**
     * 上传图片
     */
    @PostMapping("/upload")
    public ResponseEntity<ApiResponse<UploadResultDto>> uploadImage(
            @RequestParam("file") MultipartFile file,
            @RequestAttribute("userId") Long userId) throws IOException {
        log.info("用户[{}]上传图片: {}, 大小: {}", userId, file.getOriginalFilename(), file.getSize());
        UploadResultDto result = watermarkService.uploadImage(file, userId);
        return ResponseEntity.ok(ApiResponse.success("图片上传成功", result));
    }

    /**
     * 添加水印
     */
    @PostMapping("/add")
    public ResponseEntity<ApiResponse<ProcessResultDto>> addWatermark(
            @Valid @RequestBody WatermarkAddRequest request,
            @RequestAttribute("userId") Long userId) {
        log.info("用户[{}]添加水印: {}", userId, request);
        ProcessResultDto result = watermarkService.addWatermark(request, userId);
        return ResponseEntity.ok(ApiResponse.success("水印添加成功", result));
    }

    /**
     * 去除水印
     */
    @PostMapping("/remove")
    public ResponseEntity<ApiResponse<ProcessResultDto>> removeWatermark(
            @Valid @RequestBody WatermarkRemoveRequest request,
            @RequestAttribute("userId") Long userId) {
        log.info("用户[{}]去除水印: {}", userId, request);
        ProcessResultDto result = watermarkService.removeWatermark(request, userId);
        return ResponseEntity.ok(ApiResponse.success("水印去除成功", result));
    }

    /**
     * 批量处理
     */
    @PostMapping("/batch")
    public ResponseEntity<ApiResponse<String>> batchProcess(
            @Valid @RequestBody BatchProcessRequest request,
            @RequestAttribute("userId") Long userId) {
        log.info("用户[{}]批量处理: {}", userId, request);
        String taskId = watermarkService.batchProcess(request, userId);
        return ResponseEntity.ok(ApiResponse.success("批处理任务已创建", taskId));
    }

    /**
     * 获取处理状态
     */
    @GetMapping("/status/{taskId}")
    public ResponseEntity<ApiResponse<TaskStatusDto>> getTaskStatus(
            @PathVariable String taskId,
            @RequestAttribute("userId") Long userId) {
        log.info("用户[{}]查询任务状态: {}", userId, taskId);
        TaskStatusDto status = watermarkService.getTaskStatus(taskId, userId);
        return ResponseEntity.ok(ApiResponse.success("获取任务状态成功", status));
    }

    /**
     * 下载处理结果
     */
    @GetMapping("/download/{resultId}")
    public ResponseEntity<?> downloadResult(
            @PathVariable String resultId,
            @RequestAttribute("userId") Long userId) {
        log.info("用户[{}]下载处理结果: {}", userId, resultId);
        try {
            Resource resource = watermarkService.getProcessResultFile(resultId, userId);
            String contentType = determineContentType(resource.getFilename());
            
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);
        } catch (Exception e) {
            log.error("下载处理结果失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("下载处理结果失败: " + e.getMessage()));
        }
    }
    
    private String determineContentType(String filename) {
        if (filename == null) {
            return "application/octet-stream";
        }
        
        if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) {
            return "image/jpeg";
        } else if (filename.endsWith(".png")) {
            return "image/png";
        } else if (filename.endsWith(".gif")) {
            return "image/gif";
        } else if (filename.endsWith(".mp4")) {
            return "video/mp4";
        } else if (filename.endsWith(".pdf")) {
            return "application/pdf";
        } else {
            return "application/octet-stream";
        }
    }

    /**
     * 获取用户水印历史记录
     */
    @GetMapping("/history")
    public ResponseEntity<ApiResponse<List<WatermarkHistoryResponse>>> getHistory(
            @RequestAttribute("userId") Long userId,
            @RequestParam(value = "page", defaultValue = "0") int page,
            @RequestParam(value = "size", defaultValue = "10") int size) {
        log.info("用户[{}]获取水印历史记录, page={}, size={}", userId, page, size);
        List<WatermarkHistoryResponse> history = watermarkService.getUserWatermarkHistory(userId, page, size);
        return ResponseEntity.ok(ApiResponse.success("获取水印历史记录成功", history));
    }

    /**
     * 根据token上传图片
     */
    @PostMapping("/upload/token")
    public ResponseEntity<ApiResponse<UploadResultDto>> uploadImageByToken(
            @RequestParam("file") MultipartFile file,
            @RequestParam("token") String token) throws IOException {
        try {
            if (token == null || token.trim().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error("Token不能为空"));
            }
            
            // 验证token并获取用户ID
            if (!watermarkService.getAuthService().validateUserToken(token)) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(ApiResponse.error("无效的token"));
            }
            
            String userIdStr = watermarkService.getAuthService().getTokenProvider().getUserIdFromToken(token);
            Long userId = Long.valueOf(userIdStr);
            
            log.info("用户[{}]通过token上传图片: {}, 大小: {}", userId, file.getOriginalFilename(), file.getSize());
            UploadResultDto result = watermarkService.uploadImage(file, userId);
            return ResponseEntity.ok(ApiResponse.success("图片上传成功", result));
        } catch (Exception e) {
            log.error("上传图片失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("上传图片失败: " + e.getMessage()));
        }
    }
    
    /**
     * 根据token添加水印
     */
    @PostMapping("/add/token")
    public ResponseEntity<ApiResponse<ProcessResultDto>> addWatermarkByToken(
            @RequestBody Map<String, Object> requestMap) {
        try {
            // 获取token
            String token = (String) requestMap.get("token");
            if (token == null || token.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("Token不能为空"));
            }
            
            // 验证token并获取用户ID
            if (!watermarkService.getAuthService().validateUserToken(token)) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(ApiResponse.error("无效的token"));
            }
            
            String userIdStr = watermarkService.getAuthService().getTokenProvider().getUserIdFromToken(token);
            Long userId = Long.valueOf(userIdStr);
            
            // 移除token，转换为标准请求对象
            requestMap.remove("token");
            WatermarkAddRequest request = watermarkService.convertToAddRequest(requestMap);
            
            log.info("用户[{}]通过token添加水印: {}", userId, request);
            ProcessResultDto result = watermarkService.addWatermark(request, userId);
            return ResponseEntity.ok(ApiResponse.success("水印添加成功", result));
        } catch (Exception e) {
            log.error("添加水印失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("添加水印失败: " + e.getMessage()));
        }
    }
    
    /**
     * 根据token去除水印
     */
    @PostMapping("/remove/token")
    public ResponseEntity<ApiResponse<ProcessResultDto>> removeWatermarkByToken(
            @RequestBody Map<String, Object> requestMap) {
        try {
            // 获取token
            String token = (String) requestMap.get("token");
            if (token == null || token.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("Token不能为空"));
            }
            
            // 验证token并获取用户ID
            if (!watermarkService.getAuthService().validateUserToken(token)) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(ApiResponse.error("无效的token"));
            }
            
            String userIdStr = watermarkService.getAuthService().getTokenProvider().getUserIdFromToken(token);
            Long userId = Long.valueOf(userIdStr);
            
            // 移除token，转换为标准请求对象
            requestMap.remove("token");
            WatermarkRemoveRequest request = watermarkService.convertToRemoveRequest(requestMap);
            
            log.info("用户[{}]通过token去除水印: {}", userId, request);
            ProcessResultDto result = watermarkService.removeWatermark(request, userId);
            return ResponseEntity.ok(ApiResponse.success("水印去除成功", result));
        } catch (Exception e) {
            log.error("去除水印失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("去除水印失败: " + e.getMessage()));
        }
    }
    
    /**
     * 根据token批量处理
     */
    @PostMapping("/batch/token")
    public ResponseEntity<ApiResponse<String>> batchProcessByToken(
            @RequestBody Map<String, Object> requestMap) {
        try {
            // 获取token
            String token = (String) requestMap.get("token");
            if (token == null || token.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("Token不能为空"));
            }
            
            // 验证token并获取用户ID
            if (!watermarkService.getAuthService().validateUserToken(token)) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(ApiResponse.error("无效的token"));
            }
            
            String userIdStr = watermarkService.getAuthService().getTokenProvider().getUserIdFromToken(token);
            Long userId = Long.valueOf(userIdStr);
            
            // 移除token，转换为标准请求对象
            requestMap.remove("token");
            BatchProcessRequest request = watermarkService.convertToBatchRequest(requestMap);
            
            log.info("用户[{}]通过token批量处理: {}", userId, request);
            String taskId = watermarkService.batchProcess(request, userId);
            return ResponseEntity.ok(ApiResponse.success("批处理任务已创建", taskId));
        } catch (Exception e) {
            log.error("批量处理失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("批量处理失败: " + e.getMessage()));
        }
    }
    
    /**
     * 根据token获取任务状态
     */
    @PostMapping("/status/token")
    public ResponseEntity<ApiResponse<TaskStatusDto>> getTaskStatusByToken(
            @RequestBody Map<String, String> request) {
        try {
            String token = request.get("token");
            String taskId = request.get("taskId");
            
            if (token == null || token.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("Token不能为空"));
            }
            
            if (taskId == null || taskId.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("任务ID不能为空"));
            }
            
            // 验证token并获取用户ID
            if (!watermarkService.getAuthService().validateUserToken(token)) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(ApiResponse.error("无效的token"));
            }
            
            String userIdStr = watermarkService.getAuthService().getTokenProvider().getUserIdFromToken(token);
            Long userId = Long.valueOf(userIdStr);
            
            log.info("用户[{}]通过token查询任务状态: {}", userId, taskId);
            TaskStatusDto status = watermarkService.getTaskStatus(taskId, userId);
            return ResponseEntity.ok(ApiResponse.success("获取任务状态成功", status));
        } catch (Exception e) {
            log.error("获取任务状态失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("获取任务状态失败: " + e.getMessage()));
        }
    }
    
    /**
     * 根据token获取用户水印历史记录
     */
    @PostMapping("/history/token")
    public ResponseEntity<ApiResponse<List<WatermarkHistoryResponse>>> getHistoryByToken(
            @RequestBody Map<String, String> request) {
        try {
            String token = request.get("token");
            String pageStr = request.get("page");
            String sizeStr = request.get("size");
            
            if (token == null || token.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("Token不能为空"));
            }
            
            // 验证token并获取用户ID
            if (!watermarkService.getAuthService().validateUserToken(token)) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(ApiResponse.error("无效的token"));
            }
            
            String userIdStr = watermarkService.getAuthService().getTokenProvider().getUserIdFromToken(token);
            Long userId = Long.valueOf(userIdStr);
            
            int page = 0;
            int size = 10;
            
            if (pageStr != null && !pageStr.trim().isEmpty()) {
                try {
                    page = Integer.parseInt(pageStr);
                } catch (NumberFormatException e) {
                    // 使用默认值
                }
            }
            
            if (sizeStr != null && !sizeStr.trim().isEmpty()) {
                try {
                    size = Integer.parseInt(sizeStr);
                } catch (NumberFormatException e) {
                    // 使用默认值
                }
            }
            
            log.info("用户[{}]通过token获取水印历史记录, page={}, size={}", userId, page, size);
            List<WatermarkHistoryResponse> history = watermarkService.getUserWatermarkHistory(userId, page, size);
            return ResponseEntity.ok(ApiResponse.success("获取水印历史记录成功", history));
        } catch (Exception e) {
            log.error("获取水印历史记录失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("获取水印历史记录失败: " + e.getMessage()));
        }
    }
    
    /**
     * 根据token下载处理结果
     */
    @PostMapping("/download/token")
    public ResponseEntity<?> downloadResultByToken(
            @RequestBody Map<String, String> request) {
        try {
            String token = request.get("token");
            String resultId = request.get("resultId");
            
            if (token == null || token.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("Token不能为空"));
            }
            
            if (resultId == null || resultId.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("结果ID不能为空"));
            }
            
            // 验证token并获取用户ID
            if (!watermarkService.getAuthService().validateUserToken(token)) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(ApiResponse.error("无效的token"));
            }
            
            String userIdStr = watermarkService.getAuthService().getTokenProvider().getUserIdFromToken(token);
            Long userId = Long.valueOf(userIdStr);
            
            log.info("用户[{}]通过token下载处理结果: {}", userId, resultId);
            Resource resource = watermarkService.getProcessResultFile(resultId, userId);
            String contentType = determineContentType(resource.getFilename());
            
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);
        } catch (Exception e) {
            log.error("下载处理结果失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("下载处理结果失败: " + e.getMessage()));
        }
    }
} 